package com.cnbm.wcsbasic.protocol.netty.modbus.entity;



import com.cnbm.wcsbasic.protocol.netty.io.common.Utils;
import com.cnbm.wcsbasic.protocol.netty.io.common.byteutils.ByteUtils;
import com.cnbm.wcsbasic.protocol.netty.io.common.enmuc.ModbusFC;
import com.cnbm.wcsbasic.protocol.netty.io.common.enmuc.PlcVarType;

import java.util.List;

/**
 * @Desc: ""
 * @Author: caixiang
 * @DATE: 2024-04-23 9:23
 */

//应该是ReadRequestFrame 继承 Packet 类，
public class ReadRequestFrame {
    private MBAP mbap;
    //功能码 1
    private byte functionCode;
    //寄存器起始地址 2
    private byte[] address;
    //寄存器数量 2
    private byte[] unitNum;


    public ReadRequestFrame(Integer unitId, ModbusFC fc, Integer address, Integer length, Integer strSize, PlcVarType plcVarType) {
        this.mbap = new MBAP(ByteUtils.sintToBytes(unitId)[0]);
        //功能码
        this.functionCode = fc.getFread();
        //开始读的数据的地址。从00 00开始读数据  寄存器起始地址
        this.address = ByteUtils.intToBytes(address);
        //寄存器数 2个字节
        this.unitNum = Utils.getBytesNum(plcVarType, length,strSize);
    }

    public String getTransationId(){
        return mbap.getTransationId();
    }

    public byte[] toBytes(){
        List<Byte> bytes = mbap.toBytes();
        ;
        bytes.add(functionCode);
        //寄存器起始地址
        bytes.add(address[0]);
        bytes.add(address[1]);
        //寄存器数量
        bytes.add(unitNum[0]);
        bytes.add(unitNum[1]);

        byte[] result = new byte[bytes.size()];
        for(int i=0;i<bytes.size();i++){
            result[i] = bytes.get(i);
        }
        return result;

    }

}
